package edu.itla.medifacil.controllers;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import edu.itla.medifacil.helpers.Utilities;
import edu.itla.medifacil.persistence.entities.People;
import edu.itla.medifacil.persistence.enums.Attribute;
import edu.itla.medifacil.persistence.enums.Role;
import edu.itla.medifacil.persistence.managers.AssistentManager;
import edu.itla.medifacil.persistence.managers.PersonManager;


/**
 * Servlet implementation class Assistents
 */

public class Assistents extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private final AssistentManager assistentManager;  
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Assistents() {
        super();
        this.assistentManager = new AssistentManager();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession(true).removeAttribute("assistent");
		request.getSession().removeAttribute("assistentAttributes");
		request.getSession().removeAttribute("assistentDoctors");
		
		List<People> doctors  = new PersonManager().findAll( Role.DOCTOR.getId() );
		request.getSession().setAttribute("assistentDoctors", doctors);
		
		
		
		if( request.getParameter("id") != null ){
			int assistentId = Integer.parseInt( request.getParameter("id").toString() );
			People assistent = assistentManager.find(assistentId);
			prepareassistentInfo(assistent, request);
			
			if( request.getParameter("action").equals("view") )
				response.sendRedirect( "assistents/view.jsp" );
			else if( request.getParameter("action").equals("edit") )
				response.sendRedirect( "assistents/edit.jsp" );
			else if( request.getParameter("action").equals("delete") )
				assistentManager.delete( Integer.parseInt( request.getParameter("id").toString() ) );
		}else{
			List<People> assistents = assistentManager.findAll();
			request.getSession(true).removeAttribute("assistents");
			request.getSession().setAttribute("assistents", assistents);
			response.sendRedirect( "assistents/" );
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("rawtypes")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> parameters = new HashMap<String, String>();
		String cwd = request.getSession().getServletContext().getRealPath("/");
		
		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		
		if( ServletFileUpload.isMultipartContent(request) ){
			try {
				List items = uploadHandler.parseRequest(request);
				Iterator itr = items.iterator();
				while(itr.hasNext()) {
					FileItem item = (FileItem) itr.next();
					parameters.put( "attributes." + Attribute.FOTO.getId(), "/img/assistents/" + parameters.get("identification") + ".jpg");
					if(! item.isFormField() && item.getName().length() > 0 ) {
						File file = new File( cwd + "img/assistents/", parameters.get("identification") + ".jpg");
						item.write(file);
					}else{
						parameters.put(item.getFieldName(), item.getString());
					}
				}
			}catch(Exception ex) {
				log("Error encountered while parsing the request",ex);
			}
			People assistent = assistentManager.save( parameters );
			prepareassistentInfo(assistent, request);
			response.sendRedirect( "assistents/view.jsp" );
		}
	}

	
	private void prepareassistentInfo( People assistent, HttpServletRequest request ){
		Map<Integer, String> assistentAttributes = Utilities.extractPersonAttributes(assistent);
		
		request.getSession().setAttribute("assistent", assistent);
		request.getSession().setAttribute("assistentAttributes", assistentAttributes);
	}
}
